/*
 *  Copyright 2008 The MITRE Corporation (http://www.mitre.org/). All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package org.mitre.mrald.webservices;

import java.io.StringWriter;
import java.rmi.RemoteException;
import java.sql.ResultSet;
import javax.sql.rowset.WebRowSet;
import org.mitre.mrald.util.Config;
import org.mitre.mrald.util.MiscUtils;
import org.mitre.mrald.util.MraldConnection;
import org.mitre.mrald.util.RowSetFactory;


public class HandleBroadcastQuery
{

    public String handleBroadcastQuery( String datasource, String query )
    throws Exception
    {
        if (! query.toLowerCase().trim().startsWith("select ")) {
            throw new RemoteException(Config.getProperty("BaseUrl") + ": You may only perform queries through this interface.  Received: " + query);
        }
        MraldConnection conn = new MraldConnection( datasource );
        StringBuffer logInfo = new StringBuffer();
        long startTime = MiscUtils.logQuery( "remote MRALD", datasource, query, logInfo );
        ResultSet rs = conn.executeQuery( MiscUtils.clearSemiColon( query ) );
        MiscUtils.logQueryRun( startTime, logInfo );
        WebRowSet wrs = RowSetFactory.createWebRowSet();
        // wrs.populate( rs );
        // return wrs;
        StringWriter xmlString = new StringWriter();
        wrs.writeXml(rs, xmlString);
        return xmlString.toString();
    }
}




